import Vue from 'vue'
import VueRouter from 'vue-router';
import VueApollo from 'vue-apollo'

import { ApolloClient } from 'apollo-client';
import { HttpLink } from 'apollo-link-http';
import { WebSocketLink } from 'apollo-link-ws'
import { InMemoryCache } from 'apollo-cache-inmemory';
// import { ApolloLink } from 'apollo-link';
import { split } from 'apollo-link'
import { getMainDefinition } from 'apollo-utilities'

import routes from './routes/index';
import App from './App.vue'

import Element from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';

Vue.use(Element, { size: 'small', zIndex: 3000 });
Vue.use(VueRouter);
Vue.use(VueApollo)
Vue.config.productionTip = false

const router = new VueRouter({
  mode: 'history',
  routes
}) 

const httpLink = new HttpLink({
  uri: 'http://localhost:3000/graphql',
})

// 创建订阅的 websocket 连接
const wsLink = new WebSocketLink({
  uri: 'ws://localhost:3000/graphql',
  options: {
    reconnect: true,
  },
})

// const middlewareLink = new ApolloLink((operation, forward) => {
//   const token = localStorage.getItem('token');
//   operation.setContext({
//       headers: {
//           Authorization: token || null
//       }
//   });
//   return forward(operation);
// });

// 使用分割连接的功能
// 你可以根据发送的操作类型将数据发送到不同的连接
const link = split(
  // 根据操作类型分割
  ({ query }) => {
    const definition = getMainDefinition(query)
    return definition.kind === 'OperationDefinition' &&
      definition.operation === 'subscription'
  },
  wsLink,
  httpLink
)

// 创建 apollo 客户端
const apolloClient = new ApolloClient({
  // link: middlewareLink.concat(httpLink).concat(),
  link,
  cache: new InMemoryCache(),
  connectToDevTools: true
});

const apolloProvider = new VueApollo({
  defaultClient: apolloClient
})


new Vue({
  render: h => h(App),
  router,
  apolloProvider
}).$mount('#app')
